package impl

import (
	"context"

	"gitee.com/go-course/go8/projects/devcloud/cmdb/apps/host"
	"gitee.com/go-course/go8/projects/devcloud/cmdb/apps/resource"
)

func (s *service) CreateHost(ctx context.Context, req *host.Host) (*host.Host, error) {
	ins := NewHost(req)

	// 保持通用信息
	rs, err := s.resource.SaveResource(ctx, req.Resource)
	if err != nil {
		return nil, err
	}
	req.Resource = rs

	// 保持主机信息
	err = s.db.WithContext(ctx).Create(ins).Error
	if err != nil {
		return nil, err
	}

	return req, nil
}

func (s *service) QueryHost(ctx context.Context, req *host.QueryHostRequest) (
	*host.HostSet, error) {
	// 1. 先查询Host信息
	temp := NewHostSet()
	query := s.db.WithContext(ctx).Model(&Host{})
	if len(req.ResourceIds) > 0 {
		query = query.Where("resource_id IN (?)", req.ResourceIds)
	}

	err := query.
		Offset(int(req.Page.ComputeOffset())).
		Limit(int(req.Page.PageSize)).
		Scan(&temp.Items).
		Error
	if err != nil {
		return nil, err
	}

	err = query.Count(&temp.Total).Error
	if err != nil {
		return nil, err
	}
	set := temp.HostSet()

	// 2. 为这些Host补充 Resource信息
	rReq := resource.NewQueryResourceRequest()
	rReq.ResourceIds = req.ResourceIds
	rs, err := s.resource.QueryResource(ctx, rReq)
	if err != nil {
		return nil, err
	}
	set.UpdateResource(rs.Items...)

	return set, nil
}
